package com.hxht.cmp.websocket;

import com.google.gson.Gson;
import org.springframework.web.socket.server.standard.SpringConfigurator;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author alice on 2017/6/1 0001
 */
@ServerEndpoint(value = "/information",configurator = SpringConfigurator.class)
public class UserInformation {

    private static final List<Session> sessions;
    static {
        sessions = new ArrayList<>();
    }
    /**
     * web-socket查询用户的管理警报信息
     * @param message 用户id
     * @param session
     * @throws IOException
     * @throws InterruptedException
     */
    @OnMessage
    public void onMessage(String message, Session session) throws IOException, InterruptedException {
//        int count = msgService.countByUserId(message);
//        List<MsgDis tribution> list = msgService.getByUserId(message, 0, 10);
//        Map<String, Object> map = new HashMap<>();
//        map.put("count", count);
//        map.put("list", list);
        session.getBasicRemote().sendText(new Gson().toJson(null));
    }

    @OnOpen
    public void onOpen(Session session) {
        sessions.add(session);
    }

    @OnClose
    public void onClose(Session session) {
        sessions.remove(session);
        System.out.println("Connection closed");
    }

    public static void sendMessage(String message) throws IOException {
        for (Session session:sessions){
            session.getBasicRemote().sendText(message);//同步
        }
    }
}
